import {useNavigate, useParams} from "react-router-dom";
import {useEffect, useState} from "react";
import RequestUtils from "../../utils/RequestUtils";
import Apis from "../../configs/Apis";
import {Button, Card, Descriptions, Divider, Empty, message, Popconfirm, Spin, Tag, Typography} from "antd";
import {
    CalendarOutlined,
    DeleteOutlined,
    EditOutlined,
    EyeOutlined,
    HomeOutlined,
    IdcardOutlined,
    InfoCircleOutlined,
    PlusOutlined,
    UsergroupAddOutlined,
    UserOutlined,
    UserOutlined as GenderIcon
} from "@ant-design/icons";
import BackButton from "../../components/button/BackButton";
import AssignUserRoleModal from "../../components/permission/AssignUserRoleModal";
import UserEdit from "../../components/user/UserEdit";

const {Title, Text, Paragraph} = Typography;

const UserDetails = () => {
    // 操作类型和用户ID
    const {operation, userId} = useParams();

    const navigate = useNavigate();
    const [messageApi, contextHolder] = message.useMessage();
    const [loading, setLoading] = useState(true);
    const [userDetail, setUserDetail] = useState(null);
    const [userRoles, setUserRoles] = useState([]);
    const [isMobile, setIsMobile] = useState(window.innerWidth <= 768);
    const [hoveredRoleId, setHoveredRoleId] = useState(null);
    const [assignUserRoleModalVisible, setAssignUserRoleModalVisible] = useState(false);
    const [editUserParam, setEditUserParam] = useState({
        editUserModalVisible: false,
        userInfo: {}
    })

    // 响应式处理
    useEffect(() => {
        const handleResize = () => {
            setIsMobile(window.innerWidth <= 768);
        };

        window.addEventListener('resize', handleResize);
        return () => window.removeEventListener('resize', handleResize);
    }, []);

    // 基础样式 - 保持不变
    const styles = {
        container: {
            padding: isMobile ? '16px' : '24px',
        },
        card: {
            transition: 'all 0.3s ease',
            boxShadow: '0 2px 8px rgba(0, 0, 0, 0.09)',
            borderRadius: '8px',
            overflow: 'hidden',
            marginBottom: '24px',
            backgroundColor: '#fff',
        },
        cardHover: {
            boxShadow: '0 8px 24px rgba(0, 0, 0, 0.12)',
        },
        cardHeader: {
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            padding: '16px 24px',
            borderBottom: '1px solid #e8e8e8',
        },
        titleContainer: {
            display: 'flex',
            alignItems: 'center',
            gap: '8px',
        },
        loadingContainer: {
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            padding: '48px 0',
        },
        content: {
            padding: '24px',
        },
        infoContainer: {
            marginTop: '8px',
        },
        actionsContainer: {
            marginTop: '24px',
            paddingTop: '16px',
            borderTop: '1px dashed #e8e8e8',
            display: 'flex',
            justifyContent: 'flex-end',
            gap: '12px',
        },
        descriptionItem: {
            padding: '12px 16px',
        },
        descriptionContent: {
            paddingLeft: '8px',
            textAlign: isMobile ? 'left' : 'left',
        },
        tag: {
            marginLeft: '8px',
        },
        roleCardHeader: {
            display: 'flex',
            justifyContent: 'space-between',
            alignItems: 'center',
            marginBottom: '16px',
            flexWrap: 'wrap',
            gap: '12px',
        },
        roleTitle: {
            margin: 0,
            display: 'flex',
            alignItems: 'center',
            gap: '8px',
        },
        roleListContainer: {
            marginTop: '16px',
            display: 'flex',
            flexWrap: 'wrap',
            gap: '16px',
        },
        roleItem: {
            display: 'flex',
            alignItems: 'center',
            gap: '8px',
            padding: '8px 12px',
            backgroundColor: '#f9f9f9',
            borderRadius: '6px',
            transition: 'all 0.2s ease',
        },
        roleItemHover: {
            backgroundColor: '#f0f0f0',
        },
        roleTag: {
            fontSize: '14px',
            padding: '4px 10px',
            borderRadius: '4px',
        },
        addRoleButton: {
            transition: 'all 0.2s ease',
        },
        deleteRoleButton: {
            padding: '4px 8px',
            height: 'auto',
            transition: 'all 0.2s ease',
        },
        noRolesContainer: {
            padding: '24px',
            textAlign: 'center',
            color: '#666',
            backgroundColor: '#fafafa',
            borderRadius: '6px',
            margin: '16px 0',
        }
    };

    // 将数据获取逻辑提取为独立函数
    const fetchUserData = () => {
        setLoading(true);
        // 查询用户详情
        RequestUtils.post(Apis.user.searchUserById, {id: userId})
            .then(res => {
                setUserDetail(res);
                setLoading(false);
            })
            .catch(err => {
                messageApi.error("查询用户失败: " + err.message);
                setLoading(false);
                goBack2UserList();
            });

        // 查询用户角色
        RequestUtils.post(Apis.permission.searchRoleRelationByUserId, {id: userId})
            .then(res => {
                setUserRoles(res.relationRoles);
            })
            .catch(err => {
                messageApi.error("查询对应角色信息失败: " + err.message);
            });
    };

    // 初始加载数据
    useEffect(() => {
        fetchUserData();
    }, [userId, messageApi]);

    /**
     * 回到用户管理页面
     */
    const goBack2UserList = () => {
        navigate("/user");
    };

    /**
     * 编辑用户信息
     */
    const handleEdit = () => {
        navigate(`/user/edit/${userId}`);
    };

    /**
     * 添加角色
     */
    const handleAddRole = () => {
        setAssignUserRoleModalVisible(true);
    };

    /**
     * 解绑角色
     */
    const doUnbindUserRoleRelation = (roleId) => {
        RequestUtils.post(Apis.permission.unbindUserAndRole, {
            userId: userId,
            roleId: roleId
        }).then(res => {
            // 更新页面
            messageApi.success("解绑成功");
            navigate(0);
        }).catch(err => {
            messageApi.error("解绑失败，" + err.message);
        })
    };

    /**
     * 关闭模态框的回调函数，重新加载数据
     */
    const handleModalClose = () => {
        setAssignUserRoleModalVisible(false);
        // 关闭后重新加载数据，触发页面重渲染
        fetchUserData();
    };

    // 处理卡片悬停
    const [isHovered, setIsHovered] = useState(false);

    if (loading) {
        return (
            <div style={styles.container}>
                {contextHolder}
                <div style={styles.card}>
                    <div style={styles.loadingContainer}>
                        <Spin size="large" tip="加载用户信息中..."/>
                    </div>
                </div>
            </div>
        );
    }

    if (!userDetail) {
        return (
            <div style={styles.container}>
                {contextHolder}
                <div style={styles.card}>
                    <div style={styles.content}>
                        <Empty description="未找到用户信息"/>
                        <div style={styles.actionsContainer}>
                            <Button onClick={goBack2UserList}>返回</Button>
                        </div>
                    </div>
                </div>
            </div>
        );
    }

    return (
        <div style={styles.container}>
            {contextHolder}

            <BackButton message="返回上一级页面" backToLink={-1}/>

            {/* 用户基本信息卡片 */}
            <div
                style={{...styles.card, ...(isHovered ? styles.cardHover : {})}}
                onMouseEnter={() => setIsHovered(true)}
                onMouseLeave={() => setIsHovered(false)}
            >
                {/* 卡片头部 */}
                <div style={styles.cardHeader}>
                    <div style={styles.titleContainer}>
                        <Title level={4} style={{margin: 0}}>
                            用户详情
                            <Tag
                                color={operation === 'edit' ? "blue" : "green"}
                                icon={operation === 'edit' ? <EditOutlined/> : <EyeOutlined/>}
                                style={styles.tag}
                            >
                                {operation === 'edit' ? '编辑模式' : '查看模式'}
                            </Tag>
                        </Title>
                    </div>

                    {/* 操作按钮 */}
                    {operation !== 'edit' ? (
                            <Button color="cyan" variant="outlined" icon={<EditOutlined/>} onClick={handleEdit}>
                                切换到编辑模式
                            </Button>
                        ) :
                        <Button color="purple" variant="solid" icon={<EditOutlined/>}
                                onClick={() => setEditUserParam({
                                    editUserModalVisible: true,
                                    userInfo: {
                                        ...userDetail
                                    }
                                })}>
                            编辑用户资料
                        </Button>
                    }
                </div>

                {/* 卡片内容 */}
                <div style={styles.content}>
                    {/* 用户信息 */}
                    <div style={styles.infoContainer}>
                        <Descriptions
                            column={isMobile ? 1 : 2}
                            bordered
                            labelStyle={{textAlign: 'right', fontWeight: 'bold'}}
                        >
                            <Descriptions.Item
                                label="用户名"
                                icon={<UserOutlined/>}
                                style={styles.descriptionItem}
                                contentStyle={styles.descriptionContent}
                            >
                                <Text strong style={{color: 'blue'}}>{userDetail.userAccount}</Text>
                            </Descriptions.Item>

                            <Descriptions.Item
                                label="用户昵称"
                                icon={<IdcardOutlined/>}
                                style={styles.descriptionItem}
                                contentStyle={styles.descriptionContent}
                            >
                                <span style={{color: '#FF007F'}}>{userDetail.userNickname}</span>
                            </Descriptions.Item>

                            <Descriptions.Item
                                label="用户性别"
                                icon={<GenderIcon/>}
                                style={styles.descriptionItem}
                                contentStyle={styles.descriptionContent}
                            >
                                {userDetail.userGenderValue === "男" ? <Tag color="blue">男</Tag> :
                                    <Tag color="red">女</Tag>}
                            </Descriptions.Item>

                            <Descriptions.Item
                                label="出生日期"
                                icon={<CalendarOutlined/>}
                                style={styles.descriptionItem}
                                contentStyle={styles.descriptionContent}
                            >
                                {userDetail.userBirthDate || '未设置'}
                            </Descriptions.Item>

                            <Descriptions.Item
                                label="所在地区"
                                icon={<HomeOutlined/>}
                                style={styles.descriptionItem}
                                contentStyle={styles.descriptionContent}
                                span={isMobile ? 1 : 2}
                            >
                                {userDetail.userAddress || '未设置'}
                            </Descriptions.Item>

                            <Descriptions.Item
                                label="个人介绍"
                                icon={<InfoCircleOutlined/>}
                                style={styles.descriptionItem}
                                contentStyle={styles.descriptionContent}
                                span={isMobile ? 1 : 2}
                            >
                                {userDetail.userIntroduction || '未填写个人介绍'}
                            </Descriptions.Item>
                        </Descriptions>
                    </div>
                </div>
            </div>

            {/* 关联角色展示卡片 */}
            <Card style={styles.card}>
                <div style={styles.content}>
                    <div style={styles.roleCardHeader}>
                        <Title level={4} style={styles.roleTitle}>
                            <UsergroupAddOutlined/>
                            当前用户已绑定的角色
                        </Title>

                        {operation === 'edit' && (
                            <Button
                                color="purple" variant="solid"
                                icon={<PlusOutlined/>}
                                style={styles.addRoleButton}
                                onClick={handleAddRole}
                            >
                                添加角色
                            </Button>
                        )}
                    </div>

                    <Divider style={{margin: '8px 0 16px 0'}}/>

                    {userRoles.length > 0 ? (
                        <div style={styles.roleListContainer}>
                            {userRoles.map((role) => (
                                <div
                                    key={role.id}
                                    style={{
                                        ...styles.roleItem,
                                        ...(hoveredRoleId === role.id ? styles.roleItemHover : {})
                                    }}
                                    onMouseEnter={() => setHoveredRoleId(role.id)}
                                    onMouseLeave={() => setHoveredRoleId(null)}
                                >
                                    <Tag
                                        color="purple"
                                        style={styles.roleTag}
                                    >
                                        {role.roleName}
                                    </Tag>

                                    <Button style={styles.deleteRoleButton} size="small" color="cyan" variant="outlined"
                                            icon={<EyeOutlined/>}
                                            onClick={() => navigate(`/permission/${role.roleId}`)}
                                    >
                                        详情
                                    </Button>

                                    {operation === 'edit' && (
                                        <Popconfirm
                                            title="解绑确认"
                                            description="是否确认要解绑该角色？"
                                            onConfirm={() => {
                                                doUnbindUserRoleRelation(role.roleId);
                                            }}
                                            okText="确认解绑"
                                            cancelText="取消"
                                        >
                                            <Button
                                                danger
                                                icon={<DeleteOutlined/>}
                                                size="small"
                                                style={styles.deleteRoleButton}
                                                onClick={() => {
                                                }}
                                            >
                                                解绑
                                            </Button>
                                        </Popconfirm>
                                    )}
                                </div>
                            ))}
                        </div>
                    ) : (
                        <div style={styles.noRolesContainer}>
                            <Paragraph>
                                当前用户尚未绑定任何角色
                                {operation === 'edit' && '，请点击"添加角色"按钮为用户分配角色'}
                            </Paragraph>
                        </div>
                    )}
                </div>
            </Card>

            {/* 为用户分配角色modal - 使用新的关闭回调 */}
            <AssignUserRoleModal
                messageApi={messageApi}
                userId={userId}
                assignUserRoleModalVisible={assignUserRoleModalVisible}
                // 使用新的关闭回调函数
                setAssignUserRoleModalVisible={handleModalClose}
                hasAssignedRoles={userRoles}
            />

            {/* 编辑用户信息modal */}
            <UserEdit
                editUserParam={editUserParam}
                setEditUserParam={setEditUserParam}
            />

        </div>
    );
};

export default UserDetails;
